package me.boot.db.mybatis.config;

import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import lombok.extern.slf4j.Slf4j;
import me.boot.db.mybatis.condition.TenantModeDatasourceCondition;
import me.boot.db.mybatis.datasource.DynamicDataSourceService;
import me.boot.db.mybatis.datasource.TenantDataSourceProvider;
import me.boot.db.mybatis.datasource.impl.DefaultTenantDataSourceLoader;
import me.boot.db.mybatis.datasource.impl.DynamicDataSourceServiceImpl;
import me.boot.db.mybatis.interceptor.tenant.TenantDatasourceModeInterceptor;
import me.boot.db.mybatis.propertites.BasicDataSourceProperties;
import me.boot.db.mybatis.propertites.DbProperties;
import me.boot.db.mybatis.propertites.TenantMode;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * 多数据源配置
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter(MybatisPlusConfiguration.class)
public class DynamicDataSourceConfiguration {

    @PostConstruct
    public void init() {
        log.info("Init DynamicDataSourceConfiguration");
    }

    /**
     * 动态数据源提供者
     *
     * @param dbProperties               master数据源配置
     * @param masterDataSourceProperties master数据源配置
     * @return 动态数据源提供者
     */
    @Bean
    public DynamicDataSourceProvider dynamicDataSourceProvider(BasicDataSourceProperties dataSourceProperties,
                                                               DbProperties dbProperties) {
        return new TenantDataSourceProvider(dataSourceProperties, dbProperties,
                new DefaultTenantDataSourceLoader(dataSourceProperties, dbProperties));
    }

    /**
     * 动态数据源管理服务
     *
     * @return 多数据源管理服务
     */
    @Bean
    public DynamicDataSourceService dynamicDataSourceService() {
        return new DynamicDataSourceServiceImpl();
    }

    /**
     * 租户独立数据源模式插件
     *
     * @return 租户独立数据源模式插件
     */
    @Bean
    @Conditional(TenantModeDatasourceCondition.class)
    public TenantDatasourceModeInterceptor tenantDatasourceModeInterceptor() {
        log.info("租户模式:{}", TenantMode.DATASOURCE.name());
        return new TenantDatasourceModeInterceptor();
    }

}
